package com.awanp3.nimbus.common.web.interceptor;

import com.awanp3.nimbus.common.core.constant.HeaderConstants;
import com.awanp3.nimbus.common.core.utils.StringUtils;
import com.awanp3.nimbus.common.json.context.TimeZoneContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.TimeZone;

/**
 * 时区拦截器
 *
 * @author 20014170
 */
public class TimeZoneInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        String clientTimezone = request.getHeader(HeaderConstants.TIME_ZONE_KEY);
        if (StringUtils.isNotEmpty(clientTimezone)) {
            TimeZoneContextHolder.setTimeZone(TimeZone.getTimeZone(clientTimezone));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) {
        TimeZoneContextHolder.clear();
    }
}
